<?php

  /**
   *
   */
class Cicp_OutputProcessor
{
    private $_rawOutput = '';
    private $_compiledOutput = '';
    private $_processors = array();
    private $_createGraph = null;

    function addOutput($output)
    {
        $this->_rawOutput .= $output;
        $this->_compiledOutput .= $this->compileOutput($output);
    }

    function createGraph(Cicp_Graph $graph) 
    {
        $this->_createGraph = $graph;
    }

    function clean()
    {
        $this->_rawOutput = '';
        $this->_compiledOutput = '';
    }

    function getOutput()
    {
        return $this->getCompiledOutput();
    }

    function compileOutput($output)
    {
        foreach ($this->_processors as $processor) {
            $output = $processor->parseOutput($output);
        }
        return $output;
    }

    function getCompiledOutput()
    {
        if ($this->_createGraph instanceof Cicp_Graph) {
            $graph = $this->_createGraph;
            $this->clean();
            $this->compileOutput($graph->toString());
            if ($graph->graphChanged()) {
                $this->addOutput($graph->getCreateString());
            }
            else {
                $this->addOutput($graph->getModifyString());
            }
        }
        return $this->_compiledOutput;
    }

    function getRawOutput()
    {
        return $this->_rawOutput;
    }

    function addProcessor(Cicp_IOProcessor_Interface $processor, $first = false)
    {
        if (!in_array($processor, $this->_processors)) {
            if ($first == true) {
                $this->_processors = array($processor) + $this->_processors;
            }
            else {
                $this->_processors[] = $processor;
            }
        }
    }
}